package retrofit;

import android.content.Context;

import com.example.a13001.shoppingmalltemplate.application.ShoppingMallTemplateApplication;
import com.example.a13001.shoppingmalltemplate.utils.CustomGsonConverterFactory;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.google.gson.GsonBuilder;

import okhttp3.OkHttpClient;
import retrofit.cookie.ReceivedCookiesInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitHelper {
    private Context mContext;
    private Retrofit mRetrofit=null;
    private static RetrofitHelper intance=null;
    CustomGsonConverterFactory factory=CustomGsonConverterFactory.create(new GsonBuilder().create());




    public static  RetrofitHelper getIntance(Context context){
        if (intance == null) {
            intance=new RetrofitHelper(context);
        }
        return intance;
    }
    private RetrofitHelper(Context mContext) {
        this.mContext = mContext;
        init();
    }

    private void init() {
        resetApp();
    }

    private void resetApp() {
        ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(ShoppingMallTemplateApplication.getContext()));

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cookieJar(cookieJar)
//                .addInterceptor(new ReceivedCookiesInterceptor(ShoppingMallTemplateApplication.getContext()))
//                .addInterceptor(new ReceivedCookiesInterceptor(ShoppingMallTemplateApplication.getContext()))
                .build();
        mRetrofit=new Retrofit.Builder()
                .baseUrl(MyUtils.getMetaValue(ShoppingMallTemplateApplication.getContext(),"companyURL"))
                .addConverterFactory(factory)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
    }
    public RetrofitService getService(){
        return mRetrofit.create(RetrofitService.class);
    }
}
